using System;
using System.Collections.Generic;
using System.Configuration.Provider;
using System.Text;
using System.Web;
using System.Web.Configuration;

namespace Wave.Devices
{
	public static class DeviceService
	{
		private static DeviceProvider _provider = null;
		private static DeviceProviderCollection _providers = null;
		private static readonly object _lock = new object();

		public static DeviceProvider Provider { get { return _provider; } }

		public static DeviceProviderCollection Providers { get { return _providers; } }

		public static IDevice GetDevice(int DeviceID)
		{
			// Make sure a provider is loaded
			LoadProviders();

			// Delegate to the provider
			return _provider.GetDevice(DeviceID);
		}

		public static IDevice GetDevice(string UserAgent)
		{
			// Make sure a provider is loaded
			LoadProviders();

			// Delegate to the provider
			return _provider.GetDevice(UserAgent);
		}

		public static HashSet<IDevice> GetDevices()
		{
			// Make sure a provider is loaded
			LoadProviders();
			
			// Delegate to the provider
			return _provider.GetDevices();
		}

		private static void LoadProviders()
		{
			// Avoid claiming lock if providers are already loaded
			if (_provider == null)
			{
				lock (_lock)
				{
					// Do this again to make sure _provider is still null
					if (_provider == null)
					{
						// Get a reference to the <deviceService> section
						
						DeviceSection section = (DeviceSection)System.Configuration.ConfigurationManager.GetSection("wave/deviceService");
						
						// Load registered providers and point _provider
						// to the default provider
						_providers = new DeviceProviderCollection();
						
						ProvidersHelper.InstantiateProviders(section.Providers, _providers, typeof(DeviceProvider));
						_provider = _providers[section.DefaultProvider];

						if (_provider == null)
						{
							throw new ProviderException ("Unable to load default DeviceProvider");
						}
					}
				}
			}
		}
	}

}
